﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO.IsolatedStorage;
using System.IO;
using System.Xml.Linq;
using System.Net.NetworkInformation;

namespace Senior_Project
{
    public partial class HistoryPage : PhoneApplicationPage
    {
        App app = App.Current as App;
        UserProfile profile;
        int foodCount;

        // ##################################### OFFLINE MODE ############################################
        public HistoryPage()
        {
            InitializeComponent();

            string test;
            try
            {
                // set variable refer to IsolatedStorageFile
                using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    // set variable refer to IsolatedStorageFileStream
                    IsolatedStorageFileStream isoFileStream = myIsolatedStorage.OpenFile("TempXML.xml", FileMode.Open, FileAccess.Read);
                    using (StreamReader reader = new StreamReader(isoFileStream))
                    {
                        // read to end xml file
                        test = reader.ReadToEnd();

                        if (test != null)
                        {
                            // set element value
                            XElement element = XElement.Parse(test);
                            var items = from item in element.Descendants("food")
                                        select new Data
                                        {
                                            Weight = item.Element("weight").Value,
                                            Calory = item.Element("calory").Value,
                                            Protein = item.Element("protein").Value,
                                            Fat = item.Element("fat").Value,
                                            Carbohydrate = item.Element("carbohydrate").Value,
                                            Calcium = item.Element("calcium").Value,
                                            PhosPhorus = item.Element("phosphorus").Value,
                                            Iron = item.Element("iron").Value
                                        };

                            // sum value of each value
                            double sumWeight = 0, sumCalorie = 0, sumProtein = 0, sumFat = 0;
                            double sumCarbo = 0, sumCalcuim = 0, sumPhospho = 0, sumIron = 0;


                            // calculate SUM of nutrition data
                            foreach (var sumItems in items)
                            {
                                sumWeight += Convert.ToDouble(sumItems.Weight);
                                sumCalorie += Convert.ToDouble(sumItems.Calory);
                                sumProtein += Convert.ToDouble(sumItems.Protein);
                                sumFat += Convert.ToDouble(sumItems.Fat);
                                sumCarbo += Convert.ToDouble(sumItems.Carbohydrate);
                                sumCalcuim += Convert.ToDouble(sumItems.Calcium);
                                sumPhospho += Convert.ToDouble(sumItems.PhosPhorus);
                                sumIron += Convert.ToDouble(sumItems.Iron);
                            }

                            //show result to TextBox >> ReadOnly mode
                            weight.Text = sumWeight.ToString() + " g.";
                            calory.Text = sumCalorie.ToString() + " kcal.";
                            protein.Text = sumProtein.ToString() + " g.";
                            fat.Text = sumFat.ToString() + " g.";
                            carbo.Text = sumCarbo.ToString() + " g.";
                            calcuim.Text = sumCalcuim.ToString() + " g.";
                            phospho.Text = sumPhospho.ToString() + " g.";
                            iron.Text = sumIron.ToString() + " g.";
                        }
                        else { MessageBox.Show("file is empty !"); }
                    }
                }
            }
            catch
            {
                MessageBox.Show("you don't scan QR code");
            }
        }


        //********************************** connect web service [more history] ****************************************
        private void web_Click(object sender, System.EventArgs e)
        {
            NavigationService.Navigate(new Uri("/MoreHistoryPage.xaml", UriKind.RelativeOrAbsolute));
        }
        //**************************************************************************************************************



        //***************************** connect web service [add data to dadabase] *************************************
        private void sync_Click(object sender, System.EventArgs e)
        {
            progress.Visibility = Visibility.Visible;
            scrollview.IsEnabled = false;

            //=========================== open userXML.xml file for get uid ==================================
             // open userXML.xml file and read data
            string text;
            try
            {
                // set variable refer to IsolatedStorageFile
                using (IsolatedStorageFile myIsolatedStorage1 = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    // set variable refer to IsolatedStorageFileStream
                    IsolatedStorageFileStream isoFileStream1 = myIsolatedStorage1.OpenFile("userXML.xml", FileMode.Open);
                    using (StreamReader reader = new StreamReader(isoFileStream1))
                    {
                        // read to end file
                        text = reader.ReadToEnd();


                        // set element for feed data from userXML.xml file
                        XElement element = XElement.Parse(text);
                        var items1 = from item1 in element.Descendants("user")
                                    select profile = new UserProfile
                                    {
                                        Uid = item1.Element("uid").Value
                                    };
                        int count1 = items1.Count();
                    }
                }
            }
            catch 
            { 
                MessageBox.Show("userXML.xml not found !"); 
            }
            //================================================================================================


            //========================== open TempXML.xml file for send to database ==========================

            // check internet connection status
            if (!NetworkInterface.GetIsNetworkAvailable())
            {
                MessageBox.Show("No internet connection, please try agian later");
            }
            else
            {
                // open userXML.xml and send to database
                string test;
                try
                {
                    // set variable refer to IsolatedStorageFile
                    using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        // set variable refer to IsolatedStorageFileStream
                        IsolatedStorageFileStream isoFileStream = myIsolatedStorage.OpenFile("TempXML.xml", FileMode.Open, FileAccess.Read);
                        using (StreamReader reader = new StreamReader(isoFileStream))
                        {
                            // read to end xml file
                            test = reader.ReadToEnd();

                            if (test != null)
                            {
                                // set element value
                                XElement element = XElement.Parse(test);
                                var items = from item in element.Descendants("food")
                                            select new Data
                                            {
                                                Fid = item.Element("id").Value,
                                                Name = item.Element("name").Value,
                                                Date = item.Element("date").Value,
                                                Time = item.Element("time").Value,
                                                Weight = item.Element("weight").Value,
                                                Calory = item.Element("calory").Value,
                                                Protein = item.Element("protein").Value,
                                                Fat = item.Element("fat").Value,
                                                Carbohydrate = item.Element("carbohydrate").Value,
                                                Calcium = item.Element("calcium").Value,
                                                PhosPhorus = item.Element("phosphorus").Value,
                                                Iron = item.Element("iron").Value
                                            };
                                foodCount = items.Count();

                                // save xml file to database
                                // send each items
                                //WebClient sendClient = new WebClient();
                                foreach (var sendItems in items)
                                {
                                    // set client
                                    WebClient sendClient = new WebClient();
                                    string a = "http://" + app.url + "/tracking/mobile/adddata.php?uid=" + profile.Uid + "&fid=" + sendItems.Fid +
                                                                        "&food=" + sendItems.Name + "&date=" + sendItems.Date + "&time=" + sendItems.Time + "&weight=" + sendItems.Weight +
                                                                        "&calorie=" + sendItems.Calory + "&protein=" + sendItems.Protein + "&fat=" + sendItems.Fat +
                                                                        "&carbo=" + sendItems.Carbohydrate + "&calcium=" + sendItems.Calcium + "&phosphorus=" + sendItems.PhosPhorus +
                                                                        "&iron=" + sendItems.Iron;
                                    sendClient.OpenReadAsync(new Uri(a));
                                    sendClient.OpenReadCompleted += new OpenReadCompletedEventHandler(sendClient_OpenReadCompleted);
                                }

                                //sendClient.OpenReadCompleted += new OpenReadCompletedEventHandler(sendClient_OpenReadCompleted);

                            }
                        }
                    }
                }
                catch
                {
                    MessageBox.Show("File not found !");
                }
                //=======================================================================================
            }
	
        }

        void sendClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            // save complete
            progress.Visibility = Visibility.Collapsed;
            scrollview.IsEnabled = true;

            foodCount--;
            if (foodCount > 0)
            {
            }
            else MessageBox.Show("sync data complete !!");

            // delete TempXML.xml file
            try
            {
                using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    // delete file !!
                    myIsolatedStorage.DeleteFile("TempXML.xml");
                }
            }
            catch { MessageBox.Show("can not delete file !"); }

            // show result to TextBox >> ReadOnly mode
            weight.Text = "";
            calory.Text = "";
            protein.Text = "";
            fat.Text = "";
            carbo.Text = "";
            calcuim.Text = "";
            phospho.Text = "";
            iron.Text = "";   
        }
        //**************************************************************************************************************
    }
}